<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage as message } from 'element-plus'
import { md5Encrypt, getBase64 } from '@/common/utils'
import { uploadAvatarApi, addUserApi, deleteAvatarApi, getSuccessStatus } from '@/api/user'

type AvatarFile = {
	uid: number | string
	name: string
	status: 'ready' | 'uploading' | 'success' | 'fail'
	url: string
	[key: string]: any
}

interface stateType {
	username: string
	password: string
	name: string
	phone?: string
	description?:string
	status: 0 | 1
	avatarList: AvatarFile[]
	[key: string]: any
}
const state = reactive<stateType>({
	username: '',
	password: '',
	name: '',
	phone: '',
	description:'',
	status: 1,
	avatarList: [],
})
const formInstance = ref<FormInstance | null>(null)
const previewVisible = ref(false)
const previewUrl = ref('')
const uploadSuccess = ref(true)
const currentUploadUrl = ref('')

const formLayout = {
	style: 'margin: 0 10px',
	labelWidth: 'auto',
	labelPosition: 'left',
}

const rules = {
	username: [{ required: true, message: '请输入用户名！', trigger: 'change' }],
	password: [{ required: true, message: '请输入密码！', trigger: 'change' }],
	status: [{ required: true, message: '请选择用户状态！', trigger: 'change' }],
	phone: [{ pattern: /^\d{11}$/, message: '请输入正确格式的手机号!' }],
}

function handlePreviewAvatar(e: any) {
	//  console.log(e.raw)
	const item = state.avatarList.find((v) => v.uid == e.uid)
	previewUrl.value = item!.url
	previewVisible.value = true
}

async function handleRemoveAvatar(e: any) {
	//console.log(e, 'removebefore')
	const item = state.avatarList.find((v) => e.uid == v.uid)
	if (item && item.url) {
		const res = await deleteAvatarApi([item.url])
		if (res.code == getSuccessStatus()) {
			if (!res.data) {
				message.error('删除失败！')
				return false
			}
		} else return false
	}
}

function handleUploadChange(e: any) {
	//  console.log('change',e,state.avatarList)
	const { status } = e
	if (status === 'success' || status == 'fail') {
		// change钩子最先和最后各执行一次，最先的状态是'ready'，最后是success 或者 fail
		const item = state.avatarList[state.avatarList.length - 1]
		item.status = uploadSuccess.value ? 'success' : 'fail'
		item.url = uploadSuccess.value ? currentUploadUrl.value : ''
	}
	//   console.log(state.avatarList)
}

function handleBeforeUpload(e: any) {
	//console.log('beforeUpload',e)
	if (state.avatarList.length) {
		message.warning('只能上传一个头像，请先删除之前的！')
		return false
	}
}

async function handleUploadAvatar(e: any) {
	// console.log('upload',e, state.avatarList)
	const res = await uploadAvatarApi(e.file)
	// console.log(res)
	if (res.code == getSuccessStatus()) {
		uploadSuccess.value = true
		currentUploadUrl.value = res.data
	} else {
		uploadSuccess.value = false
		const base64 = await getBase64(e.file)
		currentUploadUrl.value = base64 as string
	}
}

function init() {
	formInstance.value?.resetFields()
	state.avatarList = []
	currentUploadUrl.value = ''
}

async function formCommit() {
	try {
		await formInstance.value?.validate()
		const params: any = { ...state, password: md5Encrypt(state.password) }
		params.avatar =state.avatarList[0]?state.avatarList[0].url:''
		delete params.avatarList
		const res = await addUserApi([params])
		if (res.code == getSuccessStatus()) {
			return true
		}
	} catch (error) {
		console.log(error)
	}
}

defineExpose({
	init,
	formCommit,
})
</script>

<template>
	<el-form :model="state" :rules="rules" v-bind="formLayout" ref="formInstance">
		<el-row :gutter="24">
			<el-col :span="12">
				<el-form-item prop="username" label="用户名">
					<el-input v-model="state.username" placeholder="用户名必须唯一" clearable />
				</el-form-item>
			</el-col>

			<el-col :span="12">
				<el-form-item prop="password" label="密码">
					<el-input type="password" v-model="state.password" placeholder="请输入密码" show-password clearable />
				</el-form-item>
			</el-col>

			<el-col :span="12">
				<el-form-item prop="name" label="昵称">
					<el-input v-model="state.prop" placeholder="请输入昵称" clearable />
				</el-form-item>
			</el-col>

			<el-col :span="12">
				<el-form-item prop="phone" label="手机号">
					<el-input v-model="state.phone" placeholder="请输入手机号" clearable />
				</el-form-item>
			</el-col>

			<el-col :span="24">
				<el-form-item prop="description" label="描述">
					<el-input v-model="state.description" placeholder="请输入描述" clearable />
				</el-form-item>
			</el-col>

			<el-col :span="12">
				<el-form-item prop="status" label="状态">
					<el-select v-model="state.status" placeholder="请选择用户状态" style="width: 100%" clearable>
						<el-option :value="1" label="启用" />
						<el-option :value="0" label="禁用" />
					</el-select>
				</el-form-item>
			</el-col>

			<el-col :span="24">
				<el-form-item prop="avatarList" label="头像">
					<el-upload
						accept=".png, .jpg, .jpeg"
						v-model:file-list="state.avatarList"
						list-type="picture-card"
						:http-request="handleUploadAvatar"
						:before-upload="handleBeforeUpload"
						:on-change="handleUploadChange"
						:before-remove="handleRemoveAvatar"
						:on-preview="handlePreviewAvatar"
						drag
					>
						<div style="text-align: center">
							<el-icon><Plus /></el-icon>
							<div style="margin-top: 8px">点击或拖拽上传</div>
						</div>
					</el-upload>
				</el-form-item>
			</el-col>
		</el-row>
	</el-form>
	<file-preview :visible="previewVisible" type="img" :url="previewUrl" box-width="50%" />
</template>
